package com.example.spring.jpa.ast.operation;


import com.example.spring.jpa.ast.AstNode;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;

/**
 * @author: orange
 * @create: 2023-07-22 17:08
 * @description: 表达式由左右两边构成。
 */
public abstract class AstDichotomyOperation implements AstOperation, AstGrammar {
    private AstNode left;

    private AstNode right;

    private String sentence;

    private static final Map<String, Class<? extends AstDichotomyOperation>> operationClass = new HashMap<>();

    static {
        ServiceLoader<AstDichotomyOperation> load = ServiceLoader.load(AstDichotomyOperation.class);
        for (AstDichotomyOperation dichotomy : load) {
            operationClass.put(dichotomy.operation(), dichotomy.getClass());
        }
    }

    @Override
    public AstNode parse() throws Exception {
        left = left.parse();
        right = right.parse();
        return this;
    }

    public static AstDichotomyOperation getInstance(String operation)
            throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class<? extends AstDichotomyOperation> oClass = operationClass.get(operation);
        return oClass.getDeclaredConstructor().newInstance();
    }

    public AstNode getRight() {
        return right;
    }

    public AstNode getLeft() {
        return left;
    }

    public void setRight(AstNode right) {
        this.right = right;
    }

    public void setLeft(AstNode left) {
        this.left = left;
    }

    @Override
    public String sentence() {
        return this.sentence;
    }

    public void setSentence(String sentence) {
        this.sentence = sentence;
    }
}
